package com.huike.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.huike.common.core.domain.model.LoginUser;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.utils.StringUtils;
import com.huike.framework.web.service.TokenService;

/**
 * token过滤器 验证token有效性
 *
 * ①①①
 * 拦截每一个新请求
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        System.out.println("JwtAuthenticationTokenFilter");
        //w:获取token，再获取其中的UUID，根据UUID从Redis中获取用户数据
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
            //获取token剩余有效时间，若不足二十分钟则重置有效时间
            tokenService.verifyToken(loginUser);
            //使用三参构造是为了设置super.setAuthenticated(true)，使之变成已认证的状态
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null,null);
            //authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //w:将认证的用户信息存入SecurityContextHolder，后续的filter如FilterSecurityInterceptor都是从SecurityContextHolder中获取认证的用户信息
            //相当于localThread
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
